// filepath: /home/debi/IdeaProjects/LearnRust/Work/basic/src/corex/pinx/pinx.rs
// stdx/pinx.rs
// CRITICAL: Pin 示例。Pin 确保数据不会移动，用于自引用结构。
// AUTO_COMMENT: 展示 Pin 的基本用法。

#[allow(dead_code)]
pub fn stdx_examples_pinx() {
    use std::marker::PhantomPinned;
    use std::pin::Pin;

    // CRITICAL: 基本 Pin 使用
    let mut value = 42;
    let pinned = Pin::new(&mut value);

    // CRITICAL: 自引用结构
    struct SelfRef {
        data: String,
        ptr: *const String,
        _pin: PhantomPinned,
    }

    impl SelfRef {
        fn new(s: String) -> Self {
            SelfRef {
                data: s,
                ptr: std::ptr::null(),
                _pin: PhantomPinned,
            }
        }

        fn init(self: Pin<&mut Self>) {
            let this = unsafe { self.get_unchecked_mut() };
            this.ptr = &this.data as *const String;
        }
    }

    let mut sr = SelfRef::new("hello".to_string());
    let mut pinned_sr = unsafe { Pin::new_unchecked(&mut sr) };
    SelfRef::init(pinned_sr.as_mut());

    let _ = (pinned, pinned_sr);
}
